<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '设备注册',
  },
}
</route>

<template>
  <view style="height: 100vh; padding: 30rpx; background-color: white">
    <view class="mb-2">选择绑定方式</view>
    <wd-segmented :options="list" v-model:value="current"></wd-segmented>

    <view class="mt-6" style="width: 100%" v-if="current === '扫码'">
      <wd-button size="large" icon="scan1" block @click="sanCode">扫码注册</wd-button>
    </view>

    <view class="mt-6" style="width: 100%" v-else>
      <wd-input type="text" v-model="deviceNo" placeholder="请输入设备号" />

      <view class="mb-2"></view>
      <wd-button size="large" block @click="bindDevice">确定</wd-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { http, httpPost } from '@/utils/http'
const { run } = useRequest(
  async () =>
    await httpPost(
      '/api/app/device/device/addDevice',
      { deviceNo: deviceNo.value },
      undefined,
      undefined,
      true,
    ),
)

const list = ref<string[]>(['扫码', '手动输入'])

const current = ref('扫码')

const deviceNo = ref<string>('')

const bindDevice = async () => {
  try {
    uni.showLoading({
      title: '绑定中',
      mask: true,
    })
    await run()
    uni.hideLoading()

    uni.showModal({
      title: '绑定成功',
      icon: 'none',
    })
    deviceNo.value = ''
  } catch (error) {
    uni.hideLoading()
    uni.showModal({
      title: error?.data?.message,
      icon: 'none',
      confirmButtonText: '确定',
      showCancel: false,
    })
  }
}

const sanCode = () => {
  // 打开相机扫码
  wx.scanCode({
    success: (res) => {
      const _no = res.path.match(/scene=([^&]+)/)[1]
      console.log('deviceNo,', _no)
      deviceNo.value = _no
      bindDevice()
    },
  })
}
</script>

<style lang="scss" scoped>
//
.text {
  margin-top: 12px;
}
</style>
